<template>
  <ych-modal
    :fullscreen="true"
    :title="title"
    :visible="visible"
    :bodyStyle="bodyStyle"
    :confirmLoading="spinning > 0"
    @ok="handleOk"
    @cancel="handleCancel"
    :cancelText="$t('m.common.button.close')">
    <a-spin :spinning="spinning > 0">

      <!-- 子表单区域 -->
      <a-tabs v-model="activeKey">
        <a-tab-pane :tab="$t('m.eform.appview.other.basic_info')" :key="defaultTabKey" :forceRender="true">
          <!-- 主表单区域 -->
          <a-form :form="form">
            <a-row>
              <a-col :span="8">
                <a-form-item :label="$t('m.eform.appview.entity.viewName')" :labelCol="colLayout3.labelCol" :wrapperCol="colLayout3.wrapperCol">
                  <a-input v-decorator="[ 'viewName', validatorRules.viewName]" placeholder=""></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item :label="$t('m.eform.appview.entity.viewCode')" :labelCol="colLayout3.labelCol" :wrapperCol="colLayout3.wrapperCol">
                  <a-input v-decorator="[ 'viewCode', validatorRules.viewCode]" placeholder=""></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item :label="$t('m.eform.apptable.entity.dsName')" :labelCol="colLayout3.labelCol" :wrapperCol="colLayout3.wrapperCol">
                  <select-ds v-decorator="[ 'dsCode', validatorRules.dsCode]" placeholder=""
                             :allow-clear="false"></select-ds>
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-form-item :label="$t('m.common.label.sort')" :labelCol="labelCol2" :wrapperCol="wrapperCol2">
                  <a-input-number v-decorator="[ 'orderNum', validatorRules.orderNum]"></a-input-number>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-form-item :label="$t('m.common.label.custom_SQL')" :labelCol="colLayout3.fixed.labelCol"
                             :wrapperCol="colLayout3.fixed.wrapperCol">
                  <ych-code-editor
                    v-decorator="['viewSql', validatorRules.viewSql]"
                    language="sql"
                    :fullScreen="true"
                    :placeholder="$t('m.common.tip.sql_warn')"
                    style="min-height: 50px"/>
                  <a-button-group>
                    <a-button @click="selectTable">{{ $t('m.common.button.selectEntityTable') }}</a-button>
                    <a-button @click="selectDbTable">{{ $t('m.common.button.selectDbTable') }}</a-button>
                    <a-button @click="parseSql" type="primary">{{ $t('m.common.button.parseSql') }}</a-button>
                  </a-button-group>
                  <span style="padding-left: 20px;">{{$t('m.eform.appview.other.parse_sql_tip')}}{{ model.tableName }}</span>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="6">
                <a-form-item :label="$t('m.eform.appview.entity.isFlow')" :labelCol="colLayout4.labelCol" :wrapperCol="colLayout4.wrapperCol">
                  <a-radio-group name="isFlow" v-decorator="['isFlow', validatorRules.isFlow]">
                    <a-radio :value="item.value" v-for="item in yesNo_text" :key="item.value">{{ item.text }}
                    </a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item :label="$t('m.eform.appview.entity.isMobileApp')" :labelCol="colLayout4.labelCol" :wrapperCol="colLayout4.wrapperCol">
                  <a-radio-group name="isMobileApp" v-decorator="['isMobileApp', validatorRules.isMobileApp]">
                    <a-radio :value="item.value" v-for="item in yesNo_text" :key="item.value">{{ item.text }}
                    </a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-tab-pane>
        <a-tab-pane :tab="$t('m.eform.appview.other.table_config')" :key="refKeys[0]" :forceRender="true">

          <vxe-toolbar>
            <template #buttons>
              <a-button type="primary" icon="plus" @click="insertRow('colTable', actAppViewColTable.dataSource, actAppViewColTable.initData, 'colCode')">{{ $t('m.common.button.add') }}</a-button>
              <span class="action-button-gap"></span>
              <a-button type="default" icon="minus" @click="deleteRow('colTable', actAppViewColTable.dataSource)">{{ $t('m.common.button.delete') }}</a-button>
            </template>
          </vxe-toolbar>

          <vxe-table
            header-align="center"
            border
            :scroll-y="{enabled: false}"
            ref="colTable"
            class="sortable-row-vxe"
            show-header-overflow
            show-overflow
            :height="height"
            :edit-rules="actAppViewColTable.validRules"
            :row-config="{isHover: true, useKey: true, keyField: 'id'}"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            :data="actAppViewColTable.dataSource">
            <vxe-column width="60" align="center">
              <template #default>
                <span class="drag-btn">
                  <i class="vxe-icon-num-list"></i>
                </span>
              </template>
            </vxe-column>
            <vxe-column type="checkbox" width="50" align="center"></vxe-column>
            <vxe-column type="seq" :title="$t('m.common.label.number')" width="50" align="center"></vxe-column>
            <vxe-column field="colCode" :title="$t('m.eform.appview.entity.colCode')" :edit-render="{name: 'input'}" :min-width="150"></vxe-column>
            <vxe-column field="colName" :title="$t('m.eform.appview.entity.colName')" :edit-render="{name: 'input'}" :min-width="150"></vxe-column>
            <vxe-column field="colType" :title="$t('m.eform.appview.entity.colType')" :edit-render="{name: 'select', options: colType}"
                        :min-width="100" align="center"></vxe-column>
            <vxe-column field="isHidden" :title="$t('m.eform.appview.entity.isHidden')" :edit-render="{}" :min-width="80" align="center">
              <template #default="{ row }">
                <vxe-checkbox v-model="row.isHidden" checked-value="N" unchecked-value="Y"
                              @change="setShowLocation"></vxe-checkbox>
              </template>
              <template #edit="{ row }">
                <vxe-checkbox v-model="row.isHidden" checked-value="N" unchecked-value="Y"
                              @change="setShowLocation"></vxe-checkbox>
              </template>
            </vxe-column>
            <vxe-column field="tuoMin" :title="$t('m.eform.appview.entity.tuoMin')" :edit-render="{name: 'select', options: tuoMin}"
                        :min-width="120" align="center"></vxe-column>
            <vxe-column field="dataConfig" :title="$t('m.eform.apptable.entity.dataConfig')" :edit-render="{name: 'input'}" :min-width="130" align="center">
              <template #default="{ row }">
                <a-badge :dot="!!row.dataConfig">
                  <a-button type="link" size="small" @click="dataConfigButton(row)">{{ $t('m.common.button.config') }}</a-button>
                </a-badge>
              </template>
              <template #edit="{ row }">
                <a-badge :dot="!!row.dataConfig">
                  <a-button type="link" size="small" @click="dataConfigButton(row)">{{ $t('m.common.button.config') }}</a-button>
                </a-badge>
              </template>
            </vxe-column>
            <vxe-column field="showLocation" :title="$t('m.eform.appview.entity.showLocation')" :min-width="120" align="center"></vxe-column>
            <vxe-column field="isQuery" :title="$t('m.eform.appview.entity.isQuery')" :edit-render="{}" :min-width="100" align="center">
              <template #default="{ row }">
                <vxe-checkbox v-model="row.isQuery" checked-value="Y" unchecked-value="N"></vxe-checkbox>
              </template>
              <template #edit="{ row }">
                <vxe-checkbox v-model="row.isQuery" checked-value="Y" unchecked-value="N"></vxe-checkbox>
              </template>
            </vxe-column>
          </vxe-table>

        </a-tab-pane>
        <a-tab-pane :tab="$t('m.eform.appview.other.button_config')" :key="refKeys[1]" :forceRender="true">

          <vxe-toolbar>
            <template #buttons>
              <a-button type="primary" icon="plus" @click="insertRow('buttonTable', actAppViewButtonTable.dataSource, actAppViewButtonTable.initData, 'openType')">{{ $t('m.common.button.add') }}</a-button>
              <span class="action-button-gap"></span>
              <a-button type="default" icon="minus" @click="deleteRow('buttonTable', actAppViewButtonTable.dataSource)">{{ $t('m.common.button.delete') }}</a-button>
            </template>
          </vxe-toolbar>

          <vxe-table
            header-align="center"
            keep-source
            border
            :scroll-y="{enabled: false}"
            ref="buttonTable"
            class="sortable-row-vxe"
            show-header-overflow
            show-overflow
            :height="height"
            :edit-rules="actAppViewButtonTable.validRules"
            :row-config="{isHover: true, useKey: true, keyField: 'id'}"
            :edit-config="{trigger: 'click', mode: 'cell', activeMethod: activeRowMethodButton}"
            :data="actAppViewButtonTable.dataSource">
            <vxe-column width="60" align="center">
              <template #default>
                <span class="drag-btn">
                  <i class="vxe-icon-num-list"></i>
                </span>
              </template>
            </vxe-column>
            <vxe-column type="checkbox" width="50" align="center"></vxe-column>
            <vxe-column type="seq" :title="$t('m.common.label.number')" width="50" align="center"></vxe-column>
            <vxe-column field="openType" :title="$t('m.eform.appview.entity.openType')" :edit-render="{name: 'select', options: openType}"
                        :min-width="120"></vxe-column>
            <vxe-column field="formName" :title="$t('m.eform.appview.entity.linkForm')" :edit-render="{}" :min-width="150">
              <template #default="{ row }">
                <span v-if="row.openType && noFormName.indexOf(row.openType) === -1">
                  {{ row.formName }}
                </span>
                <span v-else>{{$t('m.eform.appview.other.nothing')}}</span>
              </template>
              <template #edit="{ row }">
                <vxe-input v-model="row.formName" readOnly @click="selectForm(row)"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="viewName" :title="$t('m.eform.appview.entity.linkView')" :edit-render="{}" :min-width="150">
              <template #default="{ row }">
                <span v-if="row.openType && noViewName.indexOf(row.openType) === -1">
                  {{ row.viewName }}
                </span>
                <span v-else>{{$t('m.eform.appview.other.nothing')}}</span>
              </template>
              <template #edit="{ row }">
                <vxe-input v-model="row.viewName" readOnly @click="selectView(row)"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="objectName" :title="$t('m.eform.appview.entity.objectName')" :edit-render="{}" :min-width="120">
              <template #default="{ row }">
                <span v-if="row.openType && noObjectName.indexOf(row.openType) === -1">
                  {{ row.objectName }}
                </span>
                <span v-else>{{$t('m.eform.appview.other.nothing')}}</span>
              </template>
              <template #edit="{ row }">
                <vxe-input v-model="row.objectName" readOnly @click="selectObject(row)"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="outParameter" :title="$t('m.eform.appview.entity.outParameter')" :edit-render="{}" :min-width="150" align="center">
              <template #default="{ row }">
                <a-badge :dot="!!row.outParameter" v-if="needOutParameter.indexOf(row.openType) !== -1">
                  <a-button type="link" size="small" @click="outParameterInput(row)">{{
                      $t('m.common.button.config')
                    }}
                  </a-button>
                </a-badge>
                <span v-else>{{$t('m.eform.appview.other.nothing')}}</span>
              </template>
              <template #edit="{ row }">
                <a-badge :dot="!!row.outParameter" v-if="needOutParameter.indexOf(row.openType) !== -1">
                  <a-button type="link" size="small" @click="outParameterInput(row)">{{
                      $t('m.common.button.config')
                    }}
                  </a-button>
                </a-badge>
                <span v-else>{{$t('m.eform.appview.other.nothing')}}</span>
              </template>
            </vxe-column>
          </vxe-table>

        </a-tab-pane>
        <a-tab-pane :tab="$t('m.eform.appview.other.parameter_config')" :key="refKeys[2]" :forceRender="true">

          <vxe-toolbar>
            <template #buttons>
              <a-button type="primary" icon="plus"
                        @click="insertRow('inParameterTable', inParameterConfigTable.dataSource, inParameterConfigTable.initData, 'parameterKey')">
                {{ $t('m.common.button.add') }}
              </a-button>
              <span class="action-button-gap"></span>
              <a-button type="default" icon="minus"
                        @click="deleteRow('inParameterTable', inParameterConfigTable.dataSource)">{{ $t('m.common.button.delete') }}
              </a-button>
            </template>
          </vxe-toolbar>

          <vxe-table
            header-align="center"
            border
            :scroll-y="{enabled: false}"
            ref="inParameterTable"
            class="sortable-row-vxe"
            show-header-overflow
            show-overflow
            :height="height"
            :edit-rules="inParameterConfigTable.validRules"
            :row-config="{isHover: true, useKey: true, keyField: 'id'}"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            :data="inParameterConfigTable.dataSource">
            <vxe-column width="60" align="center">
              <template #default>
                <span class="drag-btn">
                  <i class="vxe-icon-num-list"></i>
                </span>
              </template>
            </vxe-column>
            <vxe-column type="checkbox" width="50" align="center"></vxe-column>
            <vxe-column type="seq" :title="$t('m.common.label.number')" width="50" align="center"></vxe-column>
            <vxe-column field="parameterKey" :title="$t('m.eform.appview.entity.parameterKey')" :edit-render="{name: 'input'}" :min-width="120"></vxe-column>
            <vxe-column field="parameterName" :title="$t('m.eform.appview.entity.parameterName')" :edit-render="{name: 'input'}" :min-width="120"></vxe-column>
            <vxe-column field="parameterType" :title="$t('m.eform.appview.entity.parameterType')"
                        :edit-render="{name: 'select', options: parameterType}" :min-width="120"
                        align="center"></vxe-column>
            <vxe-column field="isRequired" :title="$t('m.eform.appview.entity.isRequired')" :edit-render="{}" :min-width="110" align="center">
              <template #default="{ row }">
                <vxe-checkbox v-model="row.isRequired" checked-value="Y" unchecked-value="N"></vxe-checkbox>
              </template>
              <template #edit="{ row }">
                <vxe-checkbox v-model="row.isRequired" checked-value="Y" unchecked-value="N"></vxe-checkbox>
              </template>
            </vxe-column>
            <vxe-column field="defaultValue" :title="$t('m.eform.apptable.entity.colDefaultVal')"
                        :edit-render="{name: 'input'}" :min-width="120"></vxe-column>
          </vxe-table>
        </a-tab-pane>

      </a-tabs>

    </a-spin>

    <select-table-dialog ref="selectTableDialog" @selectFinished="selectTableOk"
                         :groupId="groupId"></select-table-dialog>

    <select-db-table-dialog ref="selectDbTableDialog" @selectFinished="selectDbTableOk"></select-db-table-dialog>

    <select-form-dialog ref="selectFormDialog" @selectFinished="selectFormOk" :groupId="groupId"></select-form-dialog>

    <data-config-dialog ref="dataConfigDialog" @selectFinished="dataConfigOk" :is-view="true" :isMobile="true"
                        :groupId="groupId"></data-config-dialog>

    <select-view-mobile-dialog ref="selectViewDialog" @selectFinished="selectViewOk"
                            :groupId="groupId"></select-view-mobile-dialog>

    <select-object-dialog ref="selectObjectDialog" @selectFinished="selectObjectOk"
                          :groupId="groupId"></select-object-dialog>

    <out-parameter-dialog ref="outParameterDialog" @selectFinished="outParameterOk"></out-parameter-dialog>
  </ych-modal>
</template>

<script>

import {GardLayoutMixin} from '@/mixins/GardLayoutMixin'
import {postAction, getAction} from '@/api/manage'
import {EFormConstant} from '../EFormConstant'
import SelectTableDialog from '../select/dialog/SelectTableDialog'
import SelectDbTableDialog from '../select/dialog/SelectDbTableDialog'
import SelectFormDialog from '../select/dialog/SelectFormDialog'
import DataConfigDialog from './actAppView/DataConfigDialog'
import SelectDs from '../select/tag/SelectDs'
import YchConstant from "@/api/YchConstant";
import {YchCodeEditor} from '@yuncheng/ych-components'
import {randomString} from "../../../utils/util";
import {YchVxeTableMixin} from "../../../mixins/YchVxeTableMixin";
import OutParameterDialog from "./actAppView/OutParameterDialog";
import SelectViewMobileDialog from "../select/dialog/SelectViewMobileDialog";
import SelectObjectDialog from "../select/dialog/SelectObjectDialog";

export default {
  name: 'ActAppMobileViewModal',
  mixins: [YchVxeTableMixin, GardLayoutMixin],
  components: {
    SelectTableDialog,
    SelectDbTableDialog,
    SelectFormDialog,
    DataConfigDialog,
    SelectDs,
    YchCodeEditor,
    OutParameterDialog,
    SelectObjectDialog,
    SelectViewMobileDialog,
  },
  props: {
    groupId: {
      type: String,
      required: true
    },
  },
  data() {
    const parameterKeyValid = ({cellValue, row}) => {
      if (cellValue) {
        const uniqueRow = this.inParameterConfigTable.dataSource.find(item => item.parameterKey && item.parameterKey.toLowerCase() === cellValue.toLowerCase() && item.id !== row.id)
        if (uniqueRow) {
          return new Error(this.$t('m.eform.appview.verify.parameterKey_repeat'))
        }
      }
    }
    return {
      title: this.$t('m.eform.apptable.entity.viewModel'),
      height: document.body.clientHeight - 53 - 55 - 86 - 52,
      noShowConfig: ['input', 'switch'],
      noFormName: EFormConstant.noFormName,
      noObjectName: EFormConstant.noObjectName,
      noViewName: EFormConstant.noViewName.concat(['handleAdd', 'handleAddFlow', 'handleEdit', 'handleDetailFlow', 'handleDetail']),
      needOutParameter: EFormConstant.needOutParameter,
      parameterType: EFormConstant.colTypeForParameter,
      bodyStyle: {
        paddingTop: 0
      },
      yesNo_text: EFormConstant.yesNo_text,
      colType: EFormConstant.colType,
      openType: EFormConstant.openType.filter(vo => vo.value === 'handleAdd' || vo.value === 'handleEdit' || vo.value === 'handleDetail' || vo.value === 'handleAddFlow' || vo.value === 'handleDetailFlow'|| vo.value === 'handleDel' || vo.value === 'handleOpenSubView'),
      tuoMin: EFormConstant.tuoMin,
      record: null,
      labelCol2: {
        xs: {span: 24},
        sm: {span: 12}
      },
      wrapperCol2: {
        xs: {span: 24},
        sm: {span: 12}
      },
      pageNumOptions: [{
        value: 10,
        label: 10
      }, {
        value: 20,
        label: 20
      }, {
        value: 50,
        label: 50
      }, {
        value: 100,
        label: 100
      }, {
        value: 200,
        label: 200
      }, {
        value: 500,
        label: 500
      }],
      validatorRules: {
        viewName: {
          rules: [
            {required: true, message: this.$t('m.eform.appview.verify.viewName')},
          ]
        },
        viewCode: {
          rules: [
            {required: true, message: this.$t('m.eform.appview.verify.viewCode')},
            {validator: this.checkCode}
          ]
        },
        afterScript: {},
        beforeScript: {},
        viewSql: {},
        isQuery: {
          initialValue: 'Y'
        },
        isFlow: {
          initialValue: 'N'
        },
        isMobileApp: {
          initialValue: 'N'
        },
        isLineNum: {
          initialValue: 'Y'
        },
        isPage: {
          initialValue: 'Y'
        },
        pageNum: {
          initialValue: 10
        },
        checkType: {
          initialValue: 'Y'
        },
        dsCode: {
          initialValue: 'dataSourceDefault',
          rules: [
            {required: true, message: this.$t('m.eform.appview.verify.dataSourceDefault')},
          ]
        },
        orderNum: {
          initialValue: 1 // TODO 默认值取数据库最大值+10
        },
      },
      defaultTabKey: 'actAppViewTab',
      refKeys: ['actAppViewCol', 'actAppViewButton', 'inParameterConfig'],
      activeKey: 'actAppViewTab',
      // 页面列
      actAppViewColTable: {
        dataSource: [],
        validRules: {
          colCode: [
            {required: true, message:this.$t('m.eform.appview.verify.colCode')},
          ],
          colName: [
            {required: true, message: this.$t('m.eform.appview.verify.colName')},
          ],
          colType: [
            {required: true, message: this.$t('m.eform.appview.verify.colType')},
          ],
        },
        initData: {
          colCode: '',
          colName: '',
          colType: 'varchar',
          alignType: 'center',
          colWidth: null,
          isHidden: 'N',
          isExport: 'Y',
          isEllipsis: 'N',
          fixed: 'none',
          isImport: 'Y',
          tuoMin: 'none',
          orderNum: 0,
          showType: 'input',
          dataConfig: '',
          actionConfig: '',
          importRules: '',
          queryFormat: '',
          isQuery: 'N',
          queryIsHidden: 'N',
          queryOp: 'eq',
          queryDefaultValue: '',
          queryOrder: null,
          queryCustomSql: ''
        }
      },
      // 页面按钮
      actAppViewButtonTable: {
        dataSource: [],
        validRules: {
          openType: [
            {required: true, message: this.$t('m.eform.appview.verify.openType')},
          ],
        },
        initData: {
          openType: 'handleAdd',
          buttonName: '',
          buttonType: 'toolbar',
          buttonStyle: 'default',
          buttonIcon: '',
          dialogSize: 'default',
          openConfig: 'dialog',
          formCode: '',
          formName: '',
          viewCode: '',
          viewName: '',
          objectCode: '',
          objectName: '',
          outParameter: '',
          showCondition: '',
          isExpand: 'N',
          isPermission: 'N',
          permission: '',
          openScript: '',
          beforeScript: '',
          afterScript: '',
          beforeJava: '',
          afterJava: '',
          butScriptDetails: '',
          orderNum: 0,
        }
      },
      // 入参配置
      inParameterConfigTable: {
        dataSource: [],
        validRules: {
          parameterKey: [
            {required: true, message: this.$t('m.eform.appview.verify.parameterKey')},
            {validator: parameterKeyValid},
          ],
          parameterName: [
            {required: true, message: this.$t('m.eform.appview.verify.parameterName')},
          ],
          parameterType: [
            {required: true, message: this.$t('m.eform.appview.verify.parameterType')},
          ],
        },
        initData: {
          parameterKey: '',
          parameterName: '',
          parameterType: 'varchar',
          isRequired: 'N',
          defaultValue: ''
        }
      },
      url: {
        add: YchConstant.PREFIX_EFORM + '/manage/actAppView/add',
        edit: YchConstant.PREFIX_EFORM + '/manage/actAppView/edit',
        checkCode: YchConstant.PREFIX_EFORM + '/manage/actAppView/checkCode',
        actAppViewCol: {
          list: YchConstant.PREFIX_EFORM + '/manage/actAppView/queryActAppViewColByMainId'
        },
        actAppViewButton: {
          list: YchConstant.PREFIX_EFORM + '/manage/actAppView/queryActAppViewButtonByMainId'
        },
        parseSql: YchConstant.PREFIX_EFORM + '/engine/viewEngine/parseSql',
        getSelectSqlByTable: YchConstant.PREFIX_EFORM + '/engine/viewEngine/getSelectSqlByTable'
      }
    }
  },
  methods: {
    parseSql() {
      const sql = this.form.getFieldValue('viewSql')
      if (!sql) {
        this.messageUtil.warning(this.$t('m.common.tip.sql_warn'))
        return
      }
      const dsCode = this.form.getFieldValue('dsCode')
      this.spinning++
      postAction(this.url.parseSql + '?dsCode=' + dsCode, {
        sql: sql
      }).then((res) => {
        if (res.success) {
          this.initTable(res.result)
        } else {
          this.messageUtil.warning(res.message)
        }
      }).finally(() => {
        this.spinning--
      })
    },
    initTable(tables) {
      if (!tables) {
        this.messageUtil.warning(this.$t('m.common.tip.return_data_null'))
        return
      }
      let hasId = false
      let tableName = []
      tables.forEach(table => {
        table.columns.forEach(column => {
          if (column.colAlias === 'id') {
            hasId = true
          }
        })
        tableName.push(table.tableName)
      })
      if (!hasId) {
        this.messageUtil.warning(this.$t('m.eform.appview.verify.sql_parse'))
        return
      }
      const dataSource = []
      tables.forEach(table => {
        this.initColumn(table.columns, dataSource)
      })
      this.actAppViewColTable.dataSource = [...dataSource]
      this.messageUtil.success(this.$t('m.common.tip.sql_ok'))
      this.model.tableName = tableName.length > 0 ? tableName[0] : ''
      this.setShowLocation();
    },
    resetOrderNum(dataSource){
      let orderNum = 1
      if(dataSource){
        dataSource.forEach(item=>{
          item.orderNum = orderNum++
        })
      }
    },
    initColumn(columns, dataSource) {
      let orderNum = 1
      //先按当前顺序设置orderNum值
      this.resetOrderNum(this.actAppViewColTable.dataSource)
      columns.forEach(column => {
        let data = this.actAppViewColTable.dataSource.find(vo => vo.colCode === column.colAlias)
        if (data) {
          data.colName = column.colDesc
          data.colType = column.colType
          data.isHidden = (!data.isHidden || data.isHidden === 'Y') ? 'Y' : 'N'
          data.isQuery = (!data.isQuery || data.isQuery === 'N') ? 'N' : 'Y'
        } else {
          const isDefault = EFormConstant.defaultField.indexOf(column.colAlias) !== -1

          let id = randomString(32)
          data = {
            id: id,
            colCode: column.colAlias,
            colName: column.colDesc,
            colType: column.colType,
            alignType: 'center',
            isHidden: isDefault ? 'Y' : 'N',
            tuoMin: 'none',
            showType: column.showType || 'input',
            dataConfig: column.dataConfig,
            orderNum: orderNum,
            isQuery: 'N',
            queryOp: 'lk'
          }
          if (data.showType === 'textarea' || data.showType === 'serialno' || data.showType === 'editor' || data.showType === 'icon' || data.showType === 'hidden') {
            data.showType = 'input'
          } else if (data.showType === 'rate' || data.showType === 'slider') {
            data.showType = 'number'
          } else if (data.showType === 'checkbox' || data.showType === 'radio') {
            data.showType = 'select'
          } else if (data.showType === 'uploadFile' || data.showType === 'uploadImg') {
            data.showType = 'input'
          }
        }
        dataSource.push(data)
        orderNum++
      })
      //按orderNum值重新排序
      dataSource.sort(function (a, b) {
        return a.orderNum < b.orderNum ? -1 : 1;
      });
    },
    selectTable() {
      const dsCode = this.form.getFieldValue('dsCode')
      this.$refs.selectTableDialog.dsCode = dsCode
      this.$refs.selectTableDialog.radio = true
      this.$refs.selectTableDialog.visible = true
    },
    selectTableOk(selectedRowKeys, selectionRows) {
      this.spinning++
      const dsCode = selectionRows[0].dsCode
      this.form.setFieldsValue({dsCode: dsCode})
      getAction(this.url.getSelectSqlByTable, {
        tableName: selectionRows[0].tableName
      }).then((res) => {
        if (res.success) {
          this.form.setFieldsValue({viewSql: res.result})
        } else {
          this.messageUtil.warning(res.message)
        }
      }).finally(() => {
        this.spinning--
      })
    },
    selectDbTable() {
      const dsCode = this.form.getFieldValue('dsCode')
      this.$refs.selectDbTableDialog.queryParam.dsCode = dsCode
      this.$refs.selectDbTableDialog.radio = true
      this.$refs.selectDbTableDialog.visible = true
    },
    selectDbTableOk(selectedRowKeys, selectionRows) {
      const dsCode = selectionRows[0].dsCode
      const sql = 'select * from ' + selectionRows[0].tableName
      this.form.setFieldsValue({dsCode: dsCode, viewSql: sql})
    },
    selectForm(record) {
      this.record = record
      this.$refs.selectFormDialog.radio = true
      this.$refs.selectFormDialog.visible = true
    },
    selectFormOk(selectedRowKeys, selectionRows) {
      const formName = selectionRows ? selectionRows[0].formName : null
      const formCode = selectionRows ? selectionRows[0].formCode : null

      this.record.formName = formName
      this.record.formCode = formCode

      this.$refs.buttonTable.updateData()
    },
    selectObject(record) {
      this.record = record
      this.$refs.selectObjectDialog.radio = true
      this.$refs.selectObjectDialog.visible = true
    },
    selectObjectOk(selectedRowKeys, selectionRows) {
      const objectName = selectionRows ? selectionRows[0].objName : null
      const objectCode = selectionRows ? selectionRows[0].objCode : null

      this.record.objectName = objectName
      this.record.objectCode = objectCode

      this.$refs.buttonTable.updateData()
    },
    outParameterInput(record) {
      this.record = record
      if (!record.viewCode) {
        this.messageUtil.warning(this.$t('m.eform.appview.verify.link_page'))
        return
      }
      this.$refs.outParameterDialog.open(record.outParameter, record.viewCode)
    },
    outParameterOk(json) {
      this.record.outParameter = json
    },
    selectView(record) {
      this.record = record
      this.$refs.selectViewDialog.radio = true
      this.$refs.selectViewDialog.visible = true
    },
    selectViewOk(selectedRowKeys, selectionRows) {
      const viewName = selectionRows ? selectionRows[0].viewName : null
      const viewCode = selectionRows ? selectionRows[0].viewCode : null

      this.record.viewName = viewName
      this.record.viewCode = viewCode

      this.$refs.buttonTable.updateData()
    },
    createDefaultBut(item, buttonStyle) {
      let id = randomString(32)
      const defaultBut = {
        id: id,
        openType: item.value,
        buttonName: item.showText || item.text,
        buttonType: item.buttonType,
        buttonStyle: buttonStyle,
        buttonIcon: item.buttonIcon,
        openConfig: 'dialog',
        dialogSize: 'default',
        isPermission: 'N',
        isExpand: 'N',
        orderNum: 0,
      }
      return defaultBut
    },
    addBefore() {
      const that = this
      this.$nextTick(() => {
        setTimeout(function () {
          const addItem = EFormConstant.openType.find(vo => vo.value === 'handleAdd')
          const editItem = EFormConstant.openType.find(vo => vo.value === 'handleEdit')
          // const delItem = EFormConstant.openType.find(vo => vo.value === 'handleDel')
          // const batchDelItem = EFormConstant.openType.find(vo => vo.value === 'handleBatchDel')

          const addBut = that.createDefaultBut(addItem, 'primary')
          const editBut = that.createDefaultBut(editItem, 'default')
          // const delBut = that.createDefaultBut(delItem, 'default')
          // const batchDelBut = that.createDefaultBut(batchDelItem, 'default')
          that.actAppViewButtonTable.dataSource = [addBut, editBut]
        }, 500)
      })
    },
    editAfter() {
      // 启用排序功能
      this.rowDrop('colTable', (newIndex, oldIndex) => {
        this.afterRowDrop(newIndex, oldIndex, this.actAppViewColTable.dataSource);
      })
      this.rowDrop('buttonTable', (newIndex, oldIndex) => {
        this.afterRowDrop(newIndex, oldIndex, this.actAppViewButtonTable.dataSource);
      })
      this.rowDrop('inParameterTable', (newIndex, oldIndex) => {
        this.afterRowDrop(newIndex, oldIndex, this.inParameterConfigTable.dataSource);
      })

      this.activeKey = this.defaultTabKey

      let fieldVal = this.lodash.pick(this.model, 'viewName', 'viewCode', 'dsCode', 'isFlow', 'viewSql', 'orderNum', 'isMobileApp')
      if (this.model.inParameter) {
        this.inParameterConfigTable.dataSource = JSON.parse(this.model.inParameter)
      } else {
        this.inParameterConfigTable.dataSource = []
      }
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldVal)
      })
      // 加载子表数据
      if (this.model.id) {
        let params = {id: this.model.id}
        this.spinning++
        getAction(this.url.actAppViewCol.list, params).then(res => {
          let {result} = res
          this.actAppViewColTable.dataSource = result || []

          this.setShowLocation();
        }).finally(() => {
          this.spinning--
        })
        this.spinning++
        getAction(this.url.actAppViewButton.list, params).then(res => {
          let {result} = res
          this.actAppViewButtonTable.dataSource = result || []
        }).finally(() => {
          this.spinning--
        })
      }
    },
    async beforeSave(formData) {
      formData.groupId = this.groupId
      formData.viewType = 'mobile'
      const tableData1 = await this.getTableDataSource(this.$refs.colTable, this.actAppViewColTable.dataSource);
      if (tableData1 === false) {
        // 返回空，终止保存动作
        this.activeKey = this.refKeys[0]
        return
      }
      const tableData2 = await this.getTableDataSource(this.$refs.buttonTable, this.actAppViewButtonTable.dataSource);
      if (tableData2 === false) {
        // 返回空，终止保存动作
        this.activeKey = this.refKeys[1]
        return
      }
      const tableData3 = await this.getTableDataSource(this.$refs.inParameterTable, this.inParameterConfigTable.dataSource);
      if (tableData3 === false) {
        // 返回空，终止保存动作
        this.activeKey = this.refKeys[2]
        return
      }
      this.resetOrderNum(this.actAppViewColTable.dataSource)
      this.resetOrderNum(this.actAppViewButtonTable.dataSource)
      formData.inParameter = JSON.stringify(this.inParameterConfigTable.dataSource)
      formData.actAppViewColList = this.actAppViewColTable.dataSource
      formData.actAppViewButtonList = this.actAppViewButtonTable.dataSource
      return formData;
    },
    setShowLocation() {
      let index = 0
      for (let i = 0; i < this.actAppViewColTable.dataSource.length; i++) {
        const vo = this.actAppViewColTable.dataSource[i]
        if (vo.isHidden === 'Y') {
          vo.showLocation = ''
        } else {
          if (index === 0) {
            vo.showLocation = this.$t('m.eform.formDesign.label.biao-ti')
          } else if (index < 3) {
            vo.showLocation = this.$t('m.eform.formDesign.label.nei-rong') + index
          } else {
            vo.showLocation = ''
          }
          index++
        }
      }
    },
    dataConfigButton(record) {
      this.record = record
      const sql = this.form.getFieldValue('viewSql')
      const dsCode = this.form.getFieldValue('dsCode')
      this.$refs.dataConfigDialog.open(record.dataConfig, record, sql, dsCode)
    },
    dataConfigOk(dataConfig) {
      this.record.dataConfig = dataConfig
    },
    checkCode(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      let reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (reg.test(value)) {
        callback(this.$t('m.common.tip.code_format'))
        return
      }
      getAction(this.url.checkCode, {
        value: value,
        id: this.model.id
      }).then((res) => {
        res.success ? callback() : callback(res.message)
      })
    },
    activeRowMethodButton({row, column}) {
      if (column.property === "dialogSize" && (!row.openType || this.needDialogSize.indexOf(row.openType) === -1)) {
        this.$refs.buttonTable.clearActived()
        return false
      }
      if (column.property === "formName" && (!row.openType || this.noFormName.indexOf(row.openType) !== -1)) {
        this.$refs.buttonTable.clearActived()
        return false
      }
      if (column.property === "viewName" && (!row.openType || this.noViewName.indexOf(row.openType) !== -1)) {
        this.$refs.buttonTable.clearActived()
        return false
      }
      if (column.property === "objectName" && (!row.openType || this.noObjectName.indexOf(row.openType) !== -1)) {
        this.$refs.buttonTable.clearActived()
        return false
      }
      return true
    },
    afterClose() {
      this.actAppViewColTable.dataSource = []
      this.actAppViewButtonTable.dataSource = []
    },
  }
}
</script>

<style lang="less" scoped>
</style>
